package com.dreamthen.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Author zengms
 * @Date 2023-10-29 14:24:52
 **/
@Configuration //配置类注解
@ComponentScan(basePackages = "com.dreamthen") //配置类扫描路径
@PropertySource("classpath:db.properties")//加载资源文件
@EnableTransactionManagement //开启事物管理器
@MapperScan("com.dreamthen.dao") //扫描mapper接口
public class AppConfig {

    @Value("${mysql.userName}")
    private String userName;

    @Value("${mysql.passWord}")
    private String passWord;

    @Value("${mysql.url}")
    private String url;

    @Value("${mysql.driverClassName}")
    private String driverClassName;

    //数据源
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(userName);
        dataSource.setPassword(passWord);
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    //myBatis的SqlSessionFactoryBean（工厂bean）
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    //事物管理器
    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}
